package com.taxshare.purchaser.service;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.mybatis.utils.DozerBeanUtil;
import com.taxshare.purchaser.constant.CodeConstant;
import com.taxshare.purchaser.constant.ResultConstant;
import com.taxshare.purchaser.entity.*;
import com.taxshare.purchaser.mapper.*;
import com.taxshare.purchaser.service.rulesReview.RulesReview;
import com.taxshare.purchaser.view.dto.InvoiceReviewRulesDTO;
import com.taxshare.purchaser.view.vo.InvoiceReviewRulesVO;
import com.taxshare.response.beans.Response;
import com.taxshare.tools.util.UUIDUitl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName: InvoiceReviewRulesService
 * @Description: 审核规则操作
 * @author: hjh
 * @date: 2021/5/11 14:46
 */
@Slf4j
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public class InvoiceReviewRulesService extends ServiceImpl<InvoiceReviewRulesMapper, InvoiceReviewRulesEntity> {
    /**
     * 税号校验
     */
    public static final String TAXNUMBER_JY = "^[A-Za-z0-9]{15,20}?$";

    @Autowired
    private InvoiceReviewRulesMapper invoiceReviewRulesMapper;

    @Autowired
    private InvoiceBlackRulesMapper invoiceBlackRulesMapper;

    @Autowired
    private InvoiceSellerRulesMapper invoiceSellerRulesMapper;

    @Autowired
    private InvoiceBuyerRulesMapper invoiceBuyerRulesMapper;

    @Autowired
    private InvoiceWhiteRulesMapper invoiceWhiteRulesMapper;

    @Autowired
    private RulesReview rulesReview;

    @Autowired
    private InvoiceGoodsRulesService invoiceGoodsRulesService;

    @Autowired
    private InvoiceAddressRulesService invoiceAddressRulesService;

    @Autowired
    private InvoiceTaxRulesService invoiceTaxRulesService;

    /**
     * 新增（更新）发票审核规则
     *
     * @param bean
     * @return
     */
    public Response addReviewRules(InvoiceReviewRulesDTO bean) {

        if (StrUtil.hasBlank(bean.getRuleName())) {
            return Response.error(ResultConstant.RET_R0001_CODE, ResultConstant.RET_R0001_MSG);
        }
        //校验传参
        if (StrUtil.hasBlank(bean.getScopeApplication())
                || (!CodeConstant.INVOICE_SCOPE_APPLICATION.contains(bean.getScopeApplication()))) {
            return Response.error(ResultConstant.RET_R0001_CODE, ResultConstant.RET_R0001_MSG);
        }
        if (CodeConstant.INVOICE_SH.equals(bean.getScopeApplication()) && StrUtil.hasBlank(bean.getTaxNumber())) {
            return Response.error(ResultConstant.RET_O0007_CODE, ResultConstant.RET_O0007_MSG);
        }
        //校验规范
//        if(!bean.getTaxNumber().matches(TAXNUMBER_JY)){
//            return Response.error(ResultConstant.RET_O0014_CODE, ResultConstant.RET_O0014_MSG);
//        }
        //首次添加
        if (StrUtil.hasBlank(bean.getUuid())) {
            InvoiceReviewRulesEntity entity = invoiceReviewRulesMapper
                    .selectOne(new QueryWrapper<InvoiceReviewRulesEntity>()
                            .eq("scope_application", bean.getScopeApplication())
                            .eq("tax_number", bean.getTaxNumber()));
            if (entity != null) {
                if (CodeConstant.INVOICE_JT.equals(bean.getScopeApplication())) {
                    return Response.error(ResultConstant.RET_O0015_CODE, ResultConstant.RET_O0015_MSG);
                }
                if (CodeConstant.INVOICE_SH.equals(bean.getScopeApplication())) {
                    return Response.error(ResultConstant.RET_R0004_CODE, ResultConstant.RET_R0004_MSG);
                }
            }
            InvoiceReviewRulesEntity copyEntity = DozerBeanUtil.map(bean, InvoiceReviewRulesEntity.class);
            copyEntity.setUuid(UUIDUitl.UUID32(false));
            int res = baseMapper.insert(copyEntity);
            if (res != 1) {
                return Response.error(ResultConstant.RET_D0001_CODE, ResultConstant.RET_D0001_MSG);
            }
            return Response.success();
        }
        //非首次更新
        QueryWrapper<InvoiceReviewRulesEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("scope_application", bean.getScopeApplication())
                .eq("tax_number", bean.getTaxNumber())
                .ne("uuid", bean.getUuid());
        if (baseMapper.selectCount(queryWrapper) > 0) {
            return Response.error(ResultConstant.RET_R0005_CODE, ResultConstant.RET_R0005_MSG);
        }
        InvoiceReviewRulesEntity entity = DozerBeanUtil.map(bean, InvoiceReviewRulesEntity.class);
        UpdateWrapper<InvoiceReviewRulesEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("uuid", bean.getUuid())
                .set("rule_name", bean.getRuleName())
                .set("scope_application", bean.getScopeApplication())
                .set("tax_number", bean.getTaxNumber());
        int result = baseMapper.update(entity, updateWrapper);
        if (result != 1) {
            return Response.error(ResultConstant.RET_D0001_CODE, ResultConstant.RET_D0001_MSG);
        }
        return Response.success();

    }

    /**
     * 查询
     *
     * @return
     */
    public Response selectList() {
        List<InvoiceReviewRulesEntity> entities = baseMapper.selectList(null);
        return Response.success(entities);
    }


    /**
     * 根据发票审核规则uuid查询联表返回InvoiceReviewRulesVO
     *
     * @param uuid
     * @return
     */
    public Response selectListById(String uuid) {
        InvoiceReviewRulesVO invoiceReviewRulesVO = new InvoiceReviewRulesVO();
        if (invoiceBlackRulesMapper.selectOne(new QueryWrapper<InvoiceBlackRulesEntity>().eq("uuid", uuid)) != null) {
            DozerBeanUtil.map(invoiceBlackRulesMapper.selectOne(new QueryWrapper<InvoiceBlackRulesEntity>().eq("uuid", uuid)), invoiceReviewRulesVO);
        }
        if (invoiceWhiteRulesMapper.selectOne(new QueryWrapper<InvoiceWhiteRulesEntity>().eq("uuid", uuid)) != null) {
            DozerBeanUtil.map(invoiceWhiteRulesMapper.selectOne(new QueryWrapper<InvoiceWhiteRulesEntity>().eq("uuid", uuid)), invoiceReviewRulesVO);
        }
        InvoiceSellerRulesEntity sellerEntity = invoiceSellerRulesMapper.selectOne(new QueryWrapper<InvoiceSellerRulesEntity>().eq("uuid", uuid));
        InvoiceBuyerRulesEntity buyerEntity = invoiceBuyerRulesMapper.selectOne(new QueryWrapper<InvoiceBuyerRulesEntity>().eq("uuid", uuid));
        InvoiceGoodsRulesEntity goodsEntity = invoiceGoodsRulesService.getOne(new QueryWrapper<InvoiceGoodsRulesEntity>().eq("uuid", uuid));
        InvoiceTaxRulesEntity taxRulesEntity = invoiceTaxRulesService.getOne(new QueryWrapper<InvoiceTaxRulesEntity>().eq("uuid", uuid));
        InvoiceAddressRulesEntity invoiceAddressRulesEntity = invoiceAddressRulesService.getOne(new QueryWrapper<InvoiceAddressRulesEntity>().eq("uuid", uuid));

        if (taxRulesEntity != null) {
            DozerBeanUtil.map(taxRulesEntity, invoiceReviewRulesVO);
            invoiceReviewRulesVO.setTaxForceFlag(taxRulesEntity.getForceFlag());
        }
        if (invoiceAddressRulesEntity != null) {
            DozerBeanUtil.map(invoiceAddressRulesEntity, invoiceReviewRulesVO);
            invoiceReviewRulesVO.setAddressForceFlag(invoiceAddressRulesEntity.getForceFlag());
        }

        if (buyerEntity != null) {
            DozerBeanUtil.map(buyerEntity, invoiceReviewRulesVO);
            if (buyerEntity.getBuyerSensitiveHead() != null) {
                invoiceReviewRulesVO.setBuyerSensitiveHeadArrays(Arrays.stream(buyerEntity.getBuyerSensitiveHead().split(",")).collect(Collectors.toList()));
            }
        }
        if (sellerEntity != null) {
            DozerBeanUtil.map(sellerEntity, invoiceReviewRulesVO);
            if (sellerEntity.getSellerSensitiveHead() != null) {
                invoiceReviewRulesVO.setSellerSensitiveHeadArrays(Arrays.stream(sellerEntity.getSellerSensitiveHead().split(",")).collect(Collectors.toList()));
            }
        }
        if (goodsEntity != null) {
            DozerBeanUtil.map(goodsEntity, invoiceReviewRulesVO);
            if (goodsEntity.getGoodsSensitiveHead() != null) {
                invoiceReviewRulesVO.setGoodsSensitiveHeadArrays(Arrays.stream(goodsEntity.getGoodsSensitiveHead().split(",")).collect(Collectors.toList()));
            }
        }


        return Response.success(invoiceReviewRulesVO);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    public Response deleteReviewRule(String id) {
        if (StrUtil.hasBlank(id)) {
            return Response.error(ResultConstant.RET_R0001_CODE, ResultConstant.RET_R0001_MSG);
        }
        int result = baseMapper.deleteById(id);
        invoiceBlackRulesMapper.delete(new QueryWrapper<InvoiceBlackRulesEntity>().eq("uuid", id));
        invoiceWhiteRulesMapper.delete(new QueryWrapper<InvoiceWhiteRulesEntity>().eq("uuid", id));
        invoiceSellerRulesMapper.delete(new QueryWrapper<InvoiceSellerRulesEntity>().eq("uuid", id));
        invoiceBuyerRulesMapper.delete(new QueryWrapper<InvoiceBuyerRulesEntity>().eq("uuid", id));
        invoiceGoodsRulesService.remove(new QueryWrapper<InvoiceGoodsRulesEntity>().eq("uuid", id));
        invoiceAddressRulesService.remove(new QueryWrapper<InvoiceAddressRulesEntity>().eq("uuid", id));
        invoiceTaxRulesService.remove(new QueryWrapper<InvoiceTaxRulesEntity>().eq("uuid", id));
        if (result != 1) {
            return Response.error(ResultConstant.RET_D0003_CODE, ResultConstant.RET_D0003_MSG);
        }
        return Response.success();
    }

    /**
     * 校验发票规则
     *
     * @param invoiceCollectionEntity 发票实体
     * @param id                      审核规则id
     * @return
     */
    public InvoiceCollectionEntity rulesReview(InvoiceCollectionEntity invoiceCollectionEntity, String id) {
       return rulesReview.checkInvoiceRules(invoiceCollectionEntity, id);
    }
}









